#coding=utf-8
import urllib
import urllib2
import httplib
import json
import os
import os.path
import urlparse
import time
import random
#导入logging保存和输出文件模板 import logging_save
import logging_save
import re
import serial
import logging
import monitor_cpumomory

class rounter_channel():
#先给路由器一个设置项
    def __init__(self,conn=httplib.HTTPConnection('192.168.1.101'),headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/html"}):
        self.Connection=conn  
        self.Headers=headers
    
    def channel_test(self):
        #先设置路由器设置项，路由器设置从0一直设置到13？如果是日本等则需要再单独考虑
        for val in range(0,2):
        #先保证连接，才方便进行后续测试（不管什么情况）
            ser_connection=serial.Serial('com6',57600,bytesize=8)
            
            ser_connection.write('ConnAp -i apcli0 DLNA2 11111111\n')
            time.sleep(1)
            ser_connection.write('ConnAp -i apcli0 DLNA2 11111111\n')
            time.sleep(1)
            
            #扣出channel的值
            url_before='http://192.168.1.1/userRpm/WlanNetworkRpm.htm?ssid1=DLNA2&mode=3&chanWidth=1&channel='
            url_after='&broadcast=2&brlssid=&brlbssid=&keytype=1&wepindex=1&authtype=1&keytext=&Save=%B1%A3+%B4%E6'
            url=url_before+str(val)+url_after
            req = urllib2.Request(url)
            req.add_header("Authorization", "Basic YWRtaW46YWRtaW4=")  #basic64 编码的admin admin
            resp = urllib2.urlopen(req)
            time.sleep(5)
            resp.close()
            logging_save.logging.info('设置路由器设置项完毕，请查收,现在测试的chann是：'+str(val))
            time.sleep(1)
            #ser_connection.write('ifconfig apcli0 192.168.1.102\n')
            #logging_save.logging.info('设置IP地址为：192.168.1.102：不过好像有问题')
             
            #长按speaker进去恢复出厂模式，长按4
            postbody_press={
                "command":"phy-key",
                "value":4
                }
            postjson=json.dumps(postbody_press)
            self.Connection.request('POST', '/api/phy-key',postjson,self.Headers)
            #getinformation=self.Connection.getresponse()
            #readinformation=getinformation.read()
            logging_save.logging.info('长按华为音乐盒播放按钮，进入恢复出厂模式。。。。。')
            time.sleep(75)
            self.Connection.close()  
            
            #通过串口往华为音乐盒写入密码，根据经验需要多写几次，否则可能失败，惨痛的教训，靠
            
            ser_connection.write('ConnAp -i apcli0 DLNA2 11111111\n')
            logging_save.logging.info('CHANNEL测试，正在往音乐盒写入用户名和密码，请耐心等待。。。。') 
            time.sleep(2)
            ser_connection.write('ConnAp -i apcli0 DLNA2 11111111\n')
            time.sleep(2)
            ser_connection.write('ConnAp -i apcli0 DLNA2 11111111\n')
            time.sleep(15)
            ser_connection.close()
            
            #判断是否ok
            if detect_connect(self)==0:
                logging_save.logging.info('正在进行的通道测试: '+str(val)+'测试成功')
                
            else:
                logging_save.logging.warning('FAIL,FAIL,FAIL,正在进行的channel测试失败:channel'+str(val))
                time.sleep(5)
                logging_save.logging.info("由于没有配对成功，故需要重新进入连接状态，请耐心等下下")
    
        #检测CPU
        monitor_cpumomory.detectmomoerycpu()
    
    
    def chanwidth(self):
        for val in range(1,4):
            #先保证连接上,测试auto,20MHZ,40MHZ
            ser_connection=serial.Serial('com6',57600,bytesize=8)
            ser_connection.write('ConnAp -i apcli0 DLNA2 11111111\n')
            time.sleep(1)
            ser_connection.write('ConnAp -i apcli0 DLNA2 11111111\n')
            time.sleep(1)
            #配置url配置channel width
            url_before='http://192.168.1.1/userRpm/WlanNetworkRpm.htm?ssid1=DLNA2&mode=3&chanWidth='
            url_after='&channel=12&broadcast=2&brlssid=&brlbssid=&keytype=1&wepindex=1&authtype=1&keytext=&Save=%B1%A3+%B4%E6'
            url=url_before+str(val)+url_after
            
            #连接urllib2 url
            req = urllib2.Request(url)
            req.add_header("Authorization", "Basic YWRtaW46YWRtaW4=")  #basic64 编码的admin admin
            resp = urllib2.urlopen(req)
            time.sleep(5)
            resp.close()
            
            #盒子进入恢复出厂设置
            postbody_press={
                "command":"phy-key",
                "value":4
                }
            postjson=json.dumps(postbody_press)
            self.Connection.request('POST', '/api/phy-key',postjson,self.Headers)
            #getinformation=self.Connection.getresponse()
            #readinformation=getinformation.read()
            logging_save.logging.info('长按华为音乐盒播放按钮，进入恢复出厂模式。。。。。')
            time.sleep(80)
            self.Connection.close()  
            #通过串口往华为音乐盒写入密码，根据经验需要多写几次，否则可能失败，惨痛的教训，靠
            ser_connection.write('ConnAp -i apcli0 DLNA2 11111111\n')
            logging_save.logging.info('正在测试channl带宽测试，正在往音乐盒写入用户名和密码，请耐心等待。。。。') 
            time.sleep(2)
            ser_connection.write('ConnAp -i apcli0 DLNA2 11111111\n')
            time.sleep(2)
            ser_connection.write('ConnAp -i apcli0 DLNA2 11111111\n')
            time.sleep(15)
            ser_connection.close()
            
            #判断是否ok
            if detect_connect(self)==0:
                logging_save.logging.info('正在进行的channel width'+str(val)+'测试成功')
                
            else:
                logging_save.logging.warning('FAIL,FAIL,FAIL,正在进行的channle widthl测试失败:channel带宽是'+str(val))
                time.sleep(5)
                logging_save.logging.info("由于没有配对成功，故需要重新进入连接状态，请耐心等下下")
                
        #检测CPU
        monitor_cpumomory.detectmomoerycpu()   
        
    def wireless_mode_test(self):
        ##先保证连接上,测试11b,11g,11n,11bg,11bgn
        logging_save.logging.info("进行wireless mode测试，测试11b,11g,11n,11bg,11bgn")
        for val in range(1,6):
            ser_connection=serial.Serial('com6',57600,bytesize=8)
            ser_connection.write('ConnAp -i apcli0 DLNA2 11111111\n')
            time.sleep(1)
            ser_connection.write('ConnAp -i apcli0 DLNA2 11111111\n')
            time.sleep(1)
        #url组合
            url_before='http://192.168.1.1/userRpm/WlanNetworkRpm.htm?ssid1=DLNA2&mode='
            url_after='&chanWidth=3&channel=12&broadcast=2&brlssid=&brlbssid=&keytype=1&wepindex=1&authtype=1&keytext=&Save=%B1%A3+%B4%E6'
            url=url_before+str(val)+url_after
        #连接urllib2 url
            req = urllib2.Request(url)
            req.add_header("Authorization", "Basic YWRtaW46YWRtaW4=")  #basic64 编码的admin admin
            resp = urllib2.urlopen(req)
            time.sleep(5)
            resp.close()
            
        #盒子进入恢复出厂设置
            postbody_press={
                "command":"phy-key",
                "value":4
                }
            postjson=json.dumps(postbody_press)
            self.Connection.request('POST', '/api/phy-key',postjson,self.Headers)
            #getinformation=self.Connection.getresponse()
            #readinformation=getinformation.read()
            logging_save.logging.info('长按华为音乐盒播放按钮，进入恢复出厂模式。。。。。')
            time.sleep(80)
            self.Connection.close()  
            
            #通过串口往华为音乐盒写入密码，根据经验需要多写几次，否则可能失败，惨痛的教训，靠
            ser_connection.write('ConnAp -i apcli0 DLNA2 11111111\n')
            logging_save.logging.info('正在测试wireless mode（802.11），正在往音乐盒写入用户名和密码，请耐心等待。。。。') 
            time.sleep(2)
            ser_connection.write('ConnAp -i apcli0 DLNA2 11111111\n')
            time.sleep(2)
            ser_connection.write('ConnAp -i apcli0 DLNA2 11111111\n')
            time.sleep(15)
            ser_connection.close()
            
        #判断是否ok
            if detect_connect(self)==0:
                logging_save.logging.info('正在进行的wireless mode：'+str(val)+'测试成功')
                
            else:
                logging_save.logging.warning('FAIL,FAIL,FAIL,正在进行的wireless model测试失败:测试mode是'+str(val))
                time.sleep(5)
                logging_save.logging.info("由于没有配对成功，故需要重新进入连接状态，请耐心等下下")       
        
        #检测CPU
        monitor_cpumomory.detectmomoerycpu() 
    
    #关机操作  
    def poweronoff(self):
        
        logging_save.logging.info("现在进入关机状态，等待10钟之后机器再开机")
        os.system(r'D:\power\power.exe com5 pw_off 6')
        time.sleep(10)
        os.system(r'D:\power\power.exe com5 pw_on 7')
        logging_save.logging.info("开机中，请耐心等待~~~~")
        time.sleep(80)
        
        if detect_connect(self)==0:
            logging_save.logging.info("依旧可以正常连接")
        
        else:
            logging_save.logging.warning('FAIL,FAIL,FAIL,无法正常连接，再确认')
        
        time.sleep(1)
        monitor_cpumomory.detectmomoerycpu()    
        
               
#def connect(self,seria_order):

#detect connect status
def detect_connect(self):
    postbody_data={
                "data":{
                "ssid":"DLNA2",
                "password":"11111111"        
                }
                }
    postjson=json.dumps(postbody_data)
    self.Connection.request('POST', '/api/hilink/smartconfig',postjson,self.Headers)
    getinformation=self.Connection.getresponse()
    readinformation=getinformation.read()
    #print readinformation
    getdeviceinfo=eval(readinformation)
    current_connect=getdeviceinfo['error_code']
    return current_connect
    self.Connection.close()  

if __name__=='__main__':
    rountertest=rounter_channel()
    #rountertest.channel_test()
    #rountertest.poweronoff()
    rountertest.chanwidth()
    #rountertest.poweronoff()
    rountertest.wireless_mode_test()
    


#
